<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use App\Libs\Util;
use App\Libs\WxSmallClient;
use iBrand\Component\Address\Address;
use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\Favorite\Favorite;
use iBrand\Component\Order\Models\Order;
use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\Component\User\Repository\MemberRepository;
use iBrand\Component\User\Models\User;
use iBrand\Component\User\Repository\UserRepository;
use iBrand\EC\Open\Server\Transformers\UserTransformer;
use iBrand\Shoppingcart\Exception;
use iBrand\Sms\Facade as Sms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Image;
use EasyWeChat;
use DB;

class UserController extends Controller
{
    private $user;
    private $order;

    const status = ["NORMAL",// 正常
        "EXPIRE", //已过期
        "GIFTING",//转赠中   DELETE 已删除，UNAVAILABLE 已失效];
        "GIFT_SUCC",// 转赠成功
        "GIFT_TIMEOUT",//转赠超时
        "DELETE",//已删除
        "UNAVAILABLE"//已失效
    ];

    const LEVEL_MAN = ['小主',// 正常
        "小王子",
        "伯爵",
        "陛下",
    ];
    const LEVEL_WOMAN= ['小主',// 正常
        "小公主", //已过期//小公主/小王子  //王妃/伯爵 女王/陛下
        "王妃",
        "女王",
    ];

    public function __construct(UserRepository $userRepository, OrderRepository $orderRepository,MemberRepository $memberRepository)
    {
        $this->user = $userRepository;
        $this->order = $orderRepository;
        $this->member = $memberRepository;
    }

    public function me()
    {
        $user = request()->user();

        return $this->response()->item($user, new UserTransformer());
    }


    public function getTryEating(){
        try{
            $user = request()->user();
            $user_id = $user->id;
            $openid = $user->openid;
            $info = DB::table('try_eating')->where(['user_id'=>$user_id,'openid'=>$openid])->first();
            if($info){
                return $this->failed('您已经参与过报名了');
            }
            $data = array_filter(request()->only(['mobile', 'sex', 'taste', 'species','home','content','work','age','name']));
            $data['user_id'] = $user_id;
            $data['openid'] = $openid;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            DB::table('try_eating')->insert($data);
            return $this->success('操作成功！');
        }catch (Exception $exception){
            return $this->failed('操作失败！');
        }

    }


    /**
     * 记录用户行为
     */
    public function getBehavior(){
        $user = request()->user();
        $arrays = request()->all();
        if(!is_array($arrays)){
            return $this->failed('缺少信息！');
        }
        $arr = [];
        foreach ($arrays as $v){
           $v['user_id'] = $user->id;
           $arr[] = $v;
        }
        DB::table('behavior_record')->insert($arr);
        return $this->success('添加成功');
    }


    public function goodGirl(){
        $user = request()->user();
        $user_id = $user->id;
        $openid = $user->openid;
        $type = request('type'); //2.白富美 1.星球
        if($type==1){
            $info = DB::table('good_girl')->where(['user_id'=>$user_id,'openid'=>$openid])->first();
        }else{
            $info = DB::table('tasting_staff')->where(['user_id'=>$user_id,'openid'=>$openid])->first();

        }
        if($info){
            return $this->failed('您已经参与过报名了');
        }
        $data = array_filter(request()->only(['name', 'age', 'sex', 'address', 'work', 'wechat_num', 'experience', 'reason', 'recommendation_code']));
        $data['user_id'] = $user_id;
        $data['openid'] = $openid;
        $data['status'] = 0;
        $data['created_at'] = date('Y-m-d H:i:s',time());
        if($type==1){
            DB::table('good_girl')->insert($data);
        }else{
            DB::table('tasting_staff')->insert($data);
        }
        return $this->success('操作成功！');
    }


    public function register(){
        $user = request()->user();
        $name = request('name');
        $mobile = request('mobile');
        $sex = request('sex');
        $age = request('age');
        $address = request('address');
        if(!isValidMobile($mobile)){
            fun_respon(0, '手机号格式不正确！');
        }
        $params = [
            'name' => $name,
            'age' => $age,
            'mobile' => $mobile,
            'sex' => $sex,
            'address' => $address,
        ];
        DB::table('ibrand_user')->where(['id'=>$user->id])->update($params);
        return $this->success('操作成功！');
    }


    /**
     * @param Request $request
     * 获取签到
     */
    public function getSigns(Request $request){
        $user = request()->user();
        $years = request('year','');
        $months = request('month','');
        $openid = $user->openid;
        $year = $years?$years:date('Y');
        $month = $months?$months:date('m');
        $sign_infos = DB::table('sign_record')->where(['openid'=>$openid,'year'=>date('Y'),'month'=>date('m')])->orderBy('id','ASC')->get(['sign_day','continuous_days','created_at'])->toArray();
        $sign_info = DB::table('sign_record')->where(['openid'=>$openid,'year'=>$year,'month'=>$month])->orderBy('id','ASC')->get(['sign_day','continuous_days','created_at'])->toArray();
        //$date = date('Y-m-d');
        $member_info = DB::table('member')->where(['openid'=>$user->openid])->first();
        if($sign_infos){
            //获取数组最后一个值
            $last = end($sign_infos);
            $continuous_days = $last->continuous_days?$last->continuous_days:0;
            //获取最后的时间 判断是否是今天 以此来控制
            if($last->sign_day==date('d',time())){
                $next_days = $continuous_days;
            }else{
                $next_days = $continuous_days+1;
            }
            if($next_days==3){
                $bonus = 8;
            }elseif($next_days==7){
                $bonus = 10;
            }elseif($next_days==15){
                $bonus = 15;
            }elseif($next_days==30){
                $bonus = 25;
            }else{
                $bonus = 5;
            }
            $sign_time = array_column($sign_info,'created_at');
            $sign_times = array_map('strtotime',$sign_time);
            fun_respon(1, ['continuous_days'=>$continuous_days,'total_bonus'=>$member_info->bonus,'next_bonus'=>$bonus,'sign_times'=>$sign_times]);
        }else{
            fun_respon(1, ['continuous_days'=>0,'total_bonus'=>$member_info->bonus,'next_bonus'=>5,'sign_times'=>[]]);
        }
    }


    /*function turntimes($v){
        return strtotime(date("Y-m-d",strtotime($v)));
    }*/

    /**
     * @param Request $request
     * 添加签到
     */
    public function addSigns(Request $request){
        $user = request()->user();
        $openid = $user->openid;
        $sign_info = DB::table('sign_record')->where(['openid'=>$openid])->orderBy('id','DESC')->first();
        $day = date('d');
        $year = date('Y');
        $month = date('m');
        $data['year'] = $year;
        $data['month'] = $month;
        $data['sign_day'] = $day;
        $data['openid'] = $openid;
        if($sign_info){
            //判断最后一条的签到记录 如果存在则判断是否为今天 ，不是则签到，如果不存在 直接添加新记录
            $date = date('Y-m-d');
            $info_date = date('Y-m-d',strtotime($sign_info->created_at));
            if($date==$info_date){
                return $this->failed( '今天已经签到过了！');
            }
            //判断签到的日期是不是每个月的第一天
            if($day=='01'){
                $data['continuous_days'] = 1;
            }else{
                //$today = strtotime($date);
                //时间差大于一天说明不是连续的
                if(($date==date('Y-m-d',strtotime("$info_date+1day")))){
                    $data['continuous_days'] = $sign_info->continuous_days+1;
                }else{
                    $data['continuous_days'] = 1;
                }
            }
            //增加积分：5分/天 连续签到3天，额外送3分；连续签到7天，额外送5分 , 连续签到15天，额外送10分；连续签到30天，额外送20分
            if($data['continuous_days']==3){
                $bonus = 8;
            }elseif($data['continuous_days']==7){
                $bonus = 10;
            }elseif($data['continuous_days']==15){
                $bonus = 15;
            }elseif($data['continuous_days']==30){
                $bonus = 25;
            }else{
                $bonus = 5;
            }
        }else{
            $data['continuous_days'] = 1;
            $bonus = 5;
        }
        //$bonus = ($data['continuous_days']%7)==0?6:5;
        $res = DB::table('sign_record')->insert($data);
        if($res){
            //添加积分
            $member_info = get_member($openid);
            if($member_info){
                $before_bonus = $member_info->bonus;
                $change_bonus = $bonus;
                $after_bonus = $before_bonus+$change_bonus;
                $status = 2;
                $type = 1;
                //更新用户的积分和皇冠
                $crown_num = intval($after_bonus/10);
                $res = DB::table('member')->where(['openid'=>$openid])->update(['bonus'=>$after_bonus,'crown_num'=>$crown_num]);
                //调用微信的接口加积分
                $record_bonus = sprintf("签到,增加积分%s", $bonus);
                $result = Util::updateMember($member_info->code,$record_bonus,$change_bonus);
                //$result = WxSmallClient::updateMember($member_info['code'],$record_bonus,$change_bonus);
                if($result['errcode']==0){
                    add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,2,'');
                }else{
                    savelog('wx_bonus', '签到加积分'.$openid.'错误：'.$result['errmsg']);
                }
            }
            return $this->success( '签到成功！');
        }
        return $this->failed( '签到失败！');
    }


    /**
     * 收集用户form_id
     */
    public function saveformid(Request $request)
    {
        try {
            $user = request()->user();
            $openid = $user->openid;
            $form_id = request('form_id');
            $data = ['openid'=>$openid, 'form_id'=>$form_id];
            $res = DB::table('user_formid')->insert($data);
            return $this->success('录入成功');
        } catch (\Exception $ex) {
            var_dump($ex->getMessage().$ex->getLine());
            fun_respon(0, '系统繁忙，请稍后再试！');
        }

    }

    public function sendTemplate(){

        $res = Redis::smembers('push_activity_no_end_66');
        Redis::srem('push_activity_no_end_66','oyybT5BSwzkX4MUHbcrSTbrCd_Po');
        var_dump($res);exit;
        $user = request()->user();
        $openid = $user->openid;
        $type = request('type');
        if($type ==1){
            $data = array(
                'keyword1'=>array('value'=>'拼团成功提醒','color'=>'#7167ce'),
                'keyword2'=>array('value'=>'您参与的暴抱团已经拼团成功啦！','color'=>'#7167ce'),
            );
        }elseif($type ==2){
            $data = array(
                'keyword1'=>array('value'=>'拼团时间快结束，未成团提醒','color'=>'#7167ce'),
                'keyword2'=>array('value'=>'您参与的暴抱团即将超时失败啦！','color'=>'#7167ce'),
            );
        }else{
            $data = array(
                'keyword1'=>array('value'=>'活动结束提醒','color'=>'#7167ce'),
                'keyword2'=>array('value'=>'截止到4月30日21点暴抱团即将结束，快看看还有啥！','color'=>'#7167ce'),
            );
        }

        $template_id = 'GcDsZ0ALQCGFmPXjVZtSD-3AZNvErBainA18W76_9bA';
        $openid = 'oyybT5BSwzkX4MUHbcrSTbrCd_Po';
        sendTemplate($openid,$data,$template_id);
    }



    //获取会员信息
    public function getMember()
    {
        try {
            $user = request()->user();
            $member_info = DB::table('member')->where(['openid' => $user->openid])->first();
            if ($member_info) {
                $type = 2;
                $officialAccount = EasyWeChat::officialAccount();

                $card = $officialAccount->card;
                $cardId = 'p2k0WuFqAtmaYGsdyE8-8C1rS9Es';
                $res = $card->member_card->getUser($cardId, $member_info->code);
                $arr['nickname'] = $res['nickname'];
                $arr['membership_number'] = $res['membership_number'];
                $arr['bonus'] = $res['bonus'];
                $arr['sex'] = $res['sex'] == 'MALE' ? 1 : 0;
                $arr['user_card_status'] = array_search($res['user_card_status'], self::status);
                //计算消费积分
                $consumer_total = $this->getbonus(['openid' => $user->openid, 'species' => 1, 'type' => 1]);
                //计算总积分
                //$total = $this->getbonus(['openid'=>$openid,'type'=>1]);
                $level = get_level($res['bonus'] / 10, $consumer_total);
                //$arr['level'] = $member_info['gender']==1?self::LEVEL_MAN[$level]:self::LEVEL_WOMAN[$level];
                $arr['level'] = $level;
                $arr['crown_num'] = intval($res['bonus'] / 10);
                $user = $this->user->find($user->id);
                $arr['avatar'] = $user->avatar;
                //更新信息
                $this->member->update($arr, $member_info->id);
            } else {
                $type = 1;
            }
            $data['type'] = $type;
            if ($member_info) {
                $level = $member_info->level ? $member_info->level : 0;
                $member_info->level = /*$member_info->sex==1?self::LEVEL_MAN[$level]:*/
                    self::LEVEL_WOMAN[$level];
                $member_info->crown_num = intval($member_info->bonus / 10);
            }
            $ress = DB::table('good_girl')->where(['openid' => $user->openid, 'status' => 1])->first();
            if ($ress) {
                //查询分销收益

                //查询今日
                $today_money = DB::table('money_record')->where(['user_id' => $user->id, 'type' => 1, 'species' => 1])->whereDay('created_at', '=', date('d'))->sum('change_money');
                $wallet['today_money'] = $today_money;
                //查询累计
                $total = DB::table('money_record')->where(['user_id' => $user->id, 'type' => 1, 'species' => 1])->sum('change_money');
                $wallet['total_money'] = $total;

                //查询未到账的金额
                $ress = DB::table('user_frozen_account')->where(['user_id' => $user->id])->first();
                $wallet['not_arrived_money'] = isset($ress->total_money) ? $ress->total_money : 0;
                //可提现金额==账户余额
                $ress = DB::table('user_account')->where(['user_id' => $user->id])->first();
                $wallet['withdraw_money'] = isset($ress->total_money) ? $ress->total_money : 0;
                $data['wallet'] = $wallet;
            }
            $data['member_info'] = $member_info;
            return $this->success($data);
        } catch (\Exception $exception) {
            DB::rollBack();
            //\Log::info($exception->getMessage() . $exception->getTraceAsString());
            savelog('user_error.log', json_encode($exception->getMessage() . $exception->getTraceAsString()));
            return $this->failed('请稍后再试！');
        }
    }

    private function getbonus($where){
        $total = DB::table('member_bonus_record')->where($where)->sum('change_bonus');
        return $total;
    }

    function get_level($total_bonus,$consume_bonus)
    {
        if ($total_bonus>=3000 && $consume_bonus>=1000){
            return 3;  //女王/陛下
        }elseif($total_bonus>=1000){
            return 2;  //王妃/伯爵
        }elseif($total_bonus>=300){
            return 1;  //小公主/小王子
        }else{
            return 0;  //小主
        }

    }


    /**xxx
     * 添加用户领卡信息
     */
    public function addMember(Request $request)
    {
        try {
            $user = request()->user();
            $openid = $user->openid;
            $code = $request->json('code');
            savelog('add_cart', ($code));
            if(!$code) fun_respon(0, '缺少会员信息！');
            $officialAccount = EasyWeChat::officialAccount();
            $card = $officialAccount->card;
            $derypt_code = $card->code->decrypt($code);
            //$data = ['openid'=>$openid, 'code'=>$derypt_code,'derypt_code'=>$code];
            /*$WxSmallClient = new WxSmallClient();
            $derypt_code = $WxSmallClient::derypt($code);*/
            $member = DB::table('member')->where(['openid'=>$openid])->first();
            if(!$member){
                $data = ['openid'=>$openid, 'code'=>$derypt_code['code'],'derypt_code'=>$code,'membership_number'=>$derypt_code['code'],'created_at'=>date('Y-m-d H:i:s',time())];
            }
            $res = $this->member->create($data);
            if($res){
                return $this->success('添加成功！');
            }
            return $this->failed('添加失败！');
        } catch (\Exception $ex) {
            var_dump($ex->getMessage().$ex->getLine());
            return $this->failed( '系统繁忙，请稍后再试！');
        }
    }


    public function getUserCards(){
        /*$user = request()->user();
        $openid = $user->openid;*/
        $officialAccount = EasyWeChat::officialAccount();
        $cardId = 'p2k0WuFqAtmaYGsdyE8-8C1rS9Es';
        //$token = $officialAccount->access_token->getToken();
       /* Redis::setex('lm_access_token_bengong_open',7000,$token['access_token']);

        $card = $officialAccount->card;
        $cardId = 'p2k0WuFqAtmaYGsdyE8-8C1rS9Es';*/

        //返回的是公众号的openid
        $res = $card->member_card->getUser($cardId, '231614306896');
        var_dump($res);
    }

    public function cardsign(){
        $card_id = request('card_id');
        $officialAccount = EasyWeChat::officialAccount();
        $card = $officialAccount->card;
        $ticket = $card->jssdk->getTicket();
        //var_dump($ticket);
        $timestamp = (string)time();
        $nonce_str = str_random(16);
        $param = [$timestamp, $nonce_str, $card_id, $ticket['ticket']];
        sort($param);
        $sign = sha1(implode('', $param));
        $res = [
            'timestamp' => $timestamp,
            'nonce_str' => $nonce_str,
            'card_id' => $card_id,
            'sign' => $sign,
        ];
        return $this->success($res);
    }


    public function show($id)
    {
        $user = $this->user->with('group')->with('size')->find($id);

        return $this->response()->item($user, new UserTransformer());
    }

    public function updateInfo()
    {
        $user = request()->user();

        $data = array_filter(request()->only(['name', 'nick_name', 'sex', 'birthday', 'city', 'education', 'qq', 'avatar', 'email', 'password']));

        if (isset($data['name']) and ($data['name']) != $user->name and User::where('name', $data['name'])->first()) {
            return $this->failed('此用户名已存在');
        }

        $user->fill($data);
        $user->save();

        return $this->success();
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     *
     */
    public function upload(Request $request){
        $file = $request->file('image');
        $destinationPath = storage_path('app/public/uploads');

        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $extension = $file->getClientOriginalExtension();
        $filename = $this->generaterandomstring() . '.' . $extension;

        $image = $file->move($destinationPath, $filename);
        /*$img = Image::make($image);
        $img->resize(320, null, function ($constraint) {
            $constraint->aspectRatio();
        })->crop(320, 320, 0, 0)->save();*/
        return $this->success(['url' => url('/storage/uploads/' . $filename)]);
    }


    public function uploadAvatar(Request $request)
    {
        //TODO: 需要验证是否传入avatar_file 参数
        $file = $request->file('avatar_file');
        $Orientation = $request->input('Orientation');

        $destinationPath = storage_path('app/public/uploads');

        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $extension = $file->getClientOriginalExtension();
        $filename = $this->generaterandomstring() . '.' . $extension;

        $image = $file->move($destinationPath, $filename);

        $img = Image::make($image);

        switch ($Orientation) {
            case 6://需要顺时针（向左）90度旋转
                $img->rotate(-90);
                break;
            case 8://需要逆时针（向右）90度旋转
                $img->rotate(90);
                break;
            case 3://需要180度旋转
                $img->rotate(180);
                break;
        }

        $img->resize(320, null, function ($constraint) {
            $constraint->aspectRatio();
        })->crop(320, 320, 0, 0)->save();

        if ('save' == request('action')) {
            $user = $request->user();
            $user->avatar = '/storage/uploads/' . $filename;
            $user->save();
        }

        return $this->success(['url' => url('/storage/uploads/' . $filename)]);
    }

    public function updateMobile(Request $request)
    {
        if (!Sms::checkCode(\request('mobile'), \request('code'))) {
            return $this->failed('验证码错误');
        }

        $user = $request->user();

        if ($existUser = $this->user->findWhere(['mobile' => request('mobile')])->first()) {
            return $this->failed('此手机号已绑定账号');
        }
        $user = $this->user->update(['mobile' => $request->input('mobile')], $user->id);

        return $this->response()->item($user, new UserTransformer());
    }

    private function generaterandomstring($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; ++$i) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        return $randomString;
    }

    public function ucenter()
    {
        $user = request()->user();
        $newCount = $this->order->getOrderCountByUserAndStatus(request()->user()->id, Order::STATUS_NEW);
        $paidCount = $this->order->getOrderCountByUserAndStatus(request()->user()->id, Order::STATUS_PAY);
        $deliveredCount = $this->order->getOrderCountByUserAndStatus(request()->user()->id, Order::STATUS_DELIVERED);
        $receiveCount = $this->order->getOrderCountByUserAndStatus(request()->user()->id, Order::STATUS_RECEIVED);

        $favCount = Favorite::where('user_id', $user->id)->count();
        $addressCount = Address::where('user_id', $user->id)->count();
        $couponCount = app(CouponRepository::class)->findActiveByUser($user->id)->count();

        return $this->success(compact('newCount', 'paidCount', 'deliveredCount', 'receiveCount', 'favCount', 'addressCount', 'couponCount'));
    }
}
